package gspushmq.v1.app.producerapp.job;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import ggframework.mongodb.BasicDBObject;
import ggframework.mongodb.DBCollection;
import ggframework.mongodb.DBCursor;
import ggframework.mongodb.DBObject;
import ggframework.util.GGConfigurer;
import gogoal.api.util.DateUtil;
import gspushmq.model.ConsumerWays;
import gspushmq.model.Data;
import gspushmq.model.DataMessage;
import gspushmq.model.PrefixEnum;
import gspushmq.util.GGLogger;
import gspushmq.util.MongoUtil;
import gspushmq.util.SysUtil;
import gspushmq.v1.app.subscribeapp.api.PushHelper;
import gspushmq.v1.app.subscribeapp.enumeration.LinkEnum;
import gspushmq.v1.app.subscribeapp.enumeration.ProductLineEnum;
import gspushmq.v1.app.subscribeapp.models.BaseVO;
import gspushmq.v1.app.subscribeapp.utils.GGPushUtil;
import gspushmq.v1.consumer.core.MessageQueue;
import gspushmq.v1.produce.job.core.GGServiceJob;
import gspushmq.v1.produce.job.hq.MonitorService;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yutao
 * @version 1.0
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2018年12月28日上午9:57:09
 * @since JDK1.7
 */
@DisallowConcurrentExecution
public class GGDehydrateJob extends GGServiceJob {

    private static String fileName = "./cache/" + PrefixEnum.DEHYDRATE.getMqSubType() + ".txt";

    @Override
    protected String setJobName(Map<String, Object> params) {
        return "脱水研报";
    }

    @Override
    public void doServiceJob(Map<String, Object> args) {
        Date lastDate;
        try {
            lastDate = SysUtil.getCacheLastDate(fileName);
        } catch (Exception e) {
            GGLogger.info(this.getClass(), "本次读取错误，不生产消息！" + e.getMessage());
            return;
        }

        //捞出最新的研报数据
        List<Map<String, Object>> list = getDehyrateData(lastDate);
        if (list == null || list.size() == 0) {
            return;
        }
        //推送APP对象（手机端关注了脱水研报的所有用户）
        Set<Long> accountIdSet = getFocus();
        Set<String> accountNames = Sets.newHashSet(GGPushUtil.getUserAccountName(accountIdSet));

        //推送PC端对象（所有用户）
        sendOnline(list);

        //处理app端推送
        sendToApp(list,accountNames);

    }

    /**
     *
     * @description app推送
     *
     * @param list
     * @param accountNames
     * @version 1.0
     * @author 成尚佳
     * @company 上海朝阳永续信息技术有限公司
     * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
     * @date 2019/1/16 9:52
     *
     */
    private static void sendToApp(List<Map<String,Object>> list,Collection<String> accountNames){
        List<String> levels = GGPushUtil.accountsMergeLimt100(Lists.newArrayList(accountNames));
        if (levels != null && levels.size() > 0) {
            //跳转地址
            String url = GGConfigurer.get("APP.YB_URL");
            List<BaseVO> tempVOs = Lists.newArrayList();
            //分批次
            for (String level : levels) {
                //每条研报
                for (Map<String, Object> yb : list) {
                    //顾虑简介html标签
                    String content = "";
                    Object sumObj = yb.get("summary");
                    if (sumObj != null) {
                        String summary = sumObj.toString();
                        summary = summary.replaceAll("<p>", "");
                        summary = summary.replaceAll("</p>", "");
                        summary = summary.replaceAll("<br/>", "");
                        Pattern pattern = Pattern.compile("<a[^<]*?>#.{1}</a>");
                        Matcher matcher2 = pattern.matcher(summary);
                        String replaceAll = matcher2.replaceAll("");
                        replaceAll.replaceAll("\\d、", "");
                        content = replaceAll;
                    }
                    //
                    BaseVO vo = new BaseVO();
                    //阿里云移动推送
                    vo.setPlate_code(9001);
                    //标题
                    vo.setMessage_title(String.valueOf(yb.get("title")));
                    //内容
                    vo.setMessage_content(content);
                    //开始推送时间
                    vo.setStart_time(new Date());
                    //过期时间
                    vo.setEnd_time(DateUtil.getBeforeMinutes(new Date(), -5));
                    //产品线281
                    vo.setSource(ProductLineEnum.ZHITOU_APP.getProductLine());
                    //系统生产入智投小秘书
                    vo.setProducer_code(7701);
                    //链接类型型
                    vo.setNotice_link_type(LinkEnum.OUTER.getCode());
                    //外链链接
                    vo.setNotice_goto_url(url + yb.get("_id"));
                    //ACCOUNT推送标识
                    vo.setTarget_code(40002);
                    //发布者
                    vo.setAuther("admin");
                    //推送对象
                    vo.setLevels(level);
                    tempVOs.add(vo);
                }
            }
            if (tempVOs.size() >0) {
                for (BaseVO vo : tempVOs) {
                    try {
                        PushHelper.pushApp(vo);
                    } catch (Exception e) {
                        GGLogger.error(GGDehydrateJob.class, "APP脱水研报推送异常："+e.getMessage());
                    }
                }
            }
        }
    }

    /**
     *
     * @description pc在线推送
     *
     * @param list
     * @param
     * @version 1.0
     * @author 成尚佳
     * @company 上海朝阳永续信息技术有限公司
     * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
     * @date 2019/1/16 9:48
     *
     */
    private static void sendOnline(List<Map<String,Object>> list){
        if (list == null || list.size() ==0){
            return;
        }
        List<Data> dataMessages = Lists.newArrayList();
        for (Map<String,Object> map : list){
            Data data = new DataMessage();
            data.setStartDate(new Date());
            data.setExpireDate(DateUtil.getDateAfterTimes(new Date(),12 * 60));
            data.setTitle(String.valueOf(map.get("title")));

            String content = "";
            Object sumObj = map.get("summary");
            if (sumObj != null) {
                String summary = sumObj.toString();
                summary = summary.replaceAll("<p>", "");
                summary = summary.replaceAll("</p>", "\n");
                summary = summary.replaceAll("<br/>", "");
                Pattern pattern = Pattern.compile("<a[^<]*?>#.{1}</a>");
                Matcher matcher2 = pattern.matcher(summary);
                String replaceAll = matcher2.replaceAll("");
                replaceAll.replaceAll("\\d、", "");
                content = replaceAll;
            }

            data.setContent(content);
            //弹窗
            data.setLinkType("2");
            data.setLinkUrl(GGConfigurer.get("PC.YB_URL")+map.get("_id"));
            //全部用户推送
            data.setCrowdType(ConsumerWays.ALL.getWay());
            data.setCrowdValue(ConsumerWays.ALL.getWay());

            data.setMqType("news");
            data.setMqSubType("dehydration_report");
            //来源(研报_id字段)
            data.setSource(map.get("_id"));
            //赋值产品线
            List<Data> tem = SysUtil.dispatherProductLine(data);
            if (tem != null && tem.size() >0) {
                dataMessages.addAll(tem);
            }
        }
        if (dataMessages.size() > 0){
            for (Data data : dataMessages){
                SysUtil.sendToMongo(data);
                MessageQueue.messageQueue.add(data);
            }
        }
    }


    /**
     *
     * @description 获取关注了脱水研报的用户，不用判断权限问题，前端自己判断
     *
     * @version 1.0
     * @author 成尚佳
     * @company 上海朝阳永续信息技术有限公司
     * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
     * @date 2019/1/14 14:15
     *
     */
    private static Set<Long> getFocus(){
        DBCollection collection = MongoUtil.getFtSuntimeFinanceCollection("cas_dehydrate_report_record");
        BasicDBObject query = new BasicDBObject();
        BasicDBObject field = new BasicDBObject();
        query.append("module", "脱水研报");
        query.append("module_code", "dehydrate");
        //关注整个脱水研报模块
        query.append("type", 1);
        query.append("status",1);
        field.append("account_id",1);
        DBCursor cursor = collection.find(query,field);
        Set<Long> sets = Sets.newHashSet();
        while (cursor.hasNext()){
            DBObject o = cursor.next();
            sets.add(o.getLong("account_id"));
        }
        cursor.close();
        return sets;
    }




    /**
     * @param lastDate
     * @return
     * @author yutao
     * @date 2018年12月28日上午9:58:30
     */
    private List<Map<String, Object>> getDehyrateData(Date lastDate) {

        //已生产脱水研报集合（id字段集合）
        Set<Object> sources = SysUtil.getSources("dehydration_report");


        DBCollection collection = MongoUtil.getFtSuntimeFinanceCollection("cs_article_secret_reference");

        BasicDBObject match = new BasicDBObject();
        match.append("plate_id", 3).append("checked", 1).append("status", 1);
        match.append("update_time", new BasicDBObject("$gt", lastDate));
        if (sources != null && sources.size() >0){
            match.append("_id",new BasicDBObject("$nin",sources));
        }



        BasicDBObject fields = new BasicDBObject();
        fields.append("title", 1).append("summary", 1).append("period", 1)
                .append("publish_date", 1).append("_id",1).append("update_time",1);

        Date temp = null;
        DBCursor cursor = collection.find(match, fields).sort(new BasicDBObject("update_time", -1));
        List<Map<String, Object>> result = new ArrayList<>();
        while (cursor.hasNext()) {
            DBObject o = cursor.next();

            if (temp == null) {
                temp = o.getDate("update_time");
            }

            result.add(o.toMap());
        }
        cursor.close();

        try {
            if (temp != null) {
                SysUtil.cacheTimeSwapToFile(temp, fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            GGLogger.info(this.getClass(), "更新入缓存时间异常:" + e.getMessage());
        }

        return result;
    }

}
